package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.Album;
import aliyun.cx.admin.service.AlbumService;
import aliyun.cx.common.util.ResponseUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 相册管理控制器
 */
@RestController
@RequestMapping("/api/album")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AlbumController {
    
    @Autowired
    private AlbumService albumService;
    
    /**
     * 分页查询相册列表
     */
    @GetMapping("/list")
    public Map<String, Object> getAlbumList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        
        try {
            Page<Album> page = albumService.getAlbumPage(current, size, name);
            return ResponseUtil.success(page);
        } catch (Exception e) {
            return ResponseUtil.error(500, "查询相册列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取相册详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getAlbumById(@PathVariable Long id) {
        try {
            Album album = albumService.getById(id);
            if (album != null) {
                return ResponseUtil.success(album);
            } else {
                return ResponseUtil.error(404, "相册不存在");
            }
        } catch (Exception e) {
            return ResponseUtil.error(500, "获取相册详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建相册
     */
    @PostMapping("/create")
    public Map<String, Object> createAlbum(@RequestBody Album album) {
        try {
            // 检查相册名称是否已存在
            if (albumService.checkAlbumExists(album.getName(), null)) {
                return ResponseUtil.error(400, "相册名称已存在");
            }
            
            boolean success = albumService.save(album);
            if (success) {
                return ResponseUtil.success("相册创建成功", album);
            } else {
                return ResponseUtil.error(500, "相册创建失败");
            }
        } catch (Exception e) {
            return ResponseUtil.error(500, "创建相册失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新相册
     */
    @PutMapping("/update")
    public Map<String, Object> updateAlbum(@RequestBody Album album) {
        try {
            // 检查相册是否存在
            Album existingAlbum = albumService.getById(album.getId());
            if (existingAlbum == null) {
                return ResponseUtil.error(404, "相册不存在");
            }
            
            // 检查相册名称是否已存在（排除当前记录）
            if (albumService.checkAlbumExists(album.getName(), album.getId())) {
                return ResponseUtil.error(400, "相册名称已存在");
            }
            
            boolean success = albumService.updateById(album);
            if (success) {
                return ResponseUtil.success("相册更新成功", album);
            } else {
                return ResponseUtil.error(500, "相册更新失败");
            }
        } catch (Exception e) {
            return ResponseUtil.error(500, "更新相册失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除相册
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteAlbum(@PathVariable Long id) {
        try {
            // 检查相册是否存在
            Album album = albumService.getById(id);
            if (album == null) {
                return ResponseUtil.error(404, "相册不存在");
            }
            
            boolean success = albumService.removeById(id);
            if (success) {
                return ResponseUtil.success(null, "相册删除成功");
            } else {
                return ResponseUtil.error(500, "相册删除失败");
            }
        } catch (Exception e) {
            return ResponseUtil.error(500, "删除相册失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除相册
     */
    @DeleteMapping("/batch")
    public Map<String, Object> batchDeleteAlbums(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            java.util.List<Long> ids = (java.util.List<Long>) params.get("ids");
            
            if (ids == null || ids.isEmpty()) {
                return ResponseUtil.error(400, "请选择要删除的相册");
            }
            
            boolean success = albumService.removeByIds(ids);
            if (success) {
                return ResponseUtil.success(null, "批量删除成功");
            } else {
                return ResponseUtil.error(500, "批量删除失败");
            }
        } catch (Exception e) {
            return ResponseUtil.error(500, "批量删除相册失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有相册（用于下拉选择）
     */
    @GetMapping("/all")
    public Map<String, Object> getAllAlbums() {
        try {
            java.util.List<Album> albums = albumService.list();
            return ResponseUtil.success(albums);
        } catch (Exception e) {
            return ResponseUtil.error(500, "获取相册列表失败：" + e.getMessage());
        }
    }
}
